package fr.gunduz.springdatamongodb.facades.impl;

import fr.gunduz.springdatamongodb.facades.IAuthorFacade;
import fr.gunduz.springdatamongodb.model.Author;
import fr.gunduz.springdatamongodb.repositories.AuthorRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 *
 * @author beytu
 */
@Service
public class AuthorFacade implements IAuthorFacade
{
	@Autowired private AuthorRepository authorRepository;
	@Autowired private MongoTemplate mongoTemplate;

	public Author add(Author author)
	{
		Assert.notNull(author,"Author to add cannot be null");
		Assert.isNull(author.getId(),"Given Author already have an ID");
		
		return authorRepository.save(author);
	}

	public Author save(Author author)
	{
		Assert.notNull(author,"Author to add cannot be null");
		Assert.notNull(author.getId(),"Given Author don't have ID");
		return authorRepository.save(author);
	}
	
	public void delete(Author author)
	{
		Assert.notNull(author,"Author to add cannot be null");
		authorRepository.delete(author);
	}

	public List<Author> search(String firstnameOrLastname)
	{
		Assert.hasText(firstnameOrLastname,"You must provide a valid title");
		Criteria criteria = new Criteria();
		criteria.orOperator(Criteria.where("firstname").is(firstnameOrLastname),Criteria.where("lastname").is(firstnameOrLastname));
		Query query = new Query(criteria);
		return mongoTemplate.find(query, Author.class);
	}

	
	
}
